/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.andersen.web.validating;

import com.andersen.web.beans.NewComponentCommandForm;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import org.springframework.stereotype.Component;
import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;

/**
 *
 * @author Corvus 11
 */
@Component
public class NewComponentValidator extends AbstractValidator{

    @Override
    public boolean supports(Class type) {
        return NewComponentCommandForm.class.isAssignableFrom(type);
    }

    @Override
    public void validate(Object obj, Errors errors) {
        NewComponentCommandForm fmt = (NewComponentCommandForm)obj;
        
            ValidationUtils.rejectIfEmptyOrWhitespace(errors, "description", "required.description", "Field is required.");
            ValidationUtils.rejectIfEmptyOrWhitespace(errors, "serial", "required.serial", "Field is required.");
            ValidationUtils.rejectIfEmptyOrWhitespace(errors, "typeId", "required.typeId", "Field is required.");

            if (fmt.getSerial().matches("^.*[^A-Z0-9].*$")) {
                errors.rejectValue("serial", "incorrect.serial");
            }

            SimpleDateFormat dateFormat = new SimpleDateFormat("dd.MM.yyyy");
            Date today = Calendar.getInstance().getTime();

            if (!fmt.getBuyDateString().isEmpty()) {
                try {
                    Date dat = dateFormat.parse(fmt.getBuyDateString());
                    if (dat.after(today))
                        errors.rejectValue("buyDateString", "notmatch.buyDate");
                } catch (ParseException ex) {
                    errors.rejectValue("buyDateString", "incorrect.buyDate");
                }
            }

            if (!fmt.getWarrantyEndDateString().isEmpty()) {
                try {
                    Date dat = dateFormat.parse(fmt.getWarrantyEndDateString());
                } catch (ParseException ex) {
                    errors.rejectValue("warrantyEndDateString", "incorrect.warrantyEndDate");
                }
            }
        
        if (fmt.getOfficeId() <= 0) {
            errors.rejectValue("officeId", "required.officeId");
        }
        
        if (fmt.getTypeId() <= 0) {
            errors.rejectValue("typeId", "required.typeId");
        }
        
        
    }
    
}
